package com.itheima.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.Date;

/**
 * @author zhangyan
 * @date 2021/2/5 17:49
 */
@Controller
@RequestMapping("/servlet")
public class ServletApiController {
    /**
     * 原生的 HttpServletRequest和HttpServletResponse都可以直接使用
     * 例如：可以直接使用HttpServletRequest对象获取请求参数
     */
    @RequestMapping("/test")
    public void test(HttpServletRequest request, HttpServletResponse response){
        //设置请求编码
        //request.setCharacterEncoding("UTF-8");
        //设置响应编码
        //response.setContentType("text/html;charset=UTF-8");

        //获取请求参数
        String id = request.getParameter("id");
        String username = request.getParameter("username");

        //数据放入域中
        request.setAttribute("nowDate", new Date());
        request.setAttribute("msg", "id:" + id + ",username:" + username);

        //重定向
        //response.sendRedirect("url");

        //请求转发
        try {
            request.getRequestDispatcher("/pages/message.jsp").forward(request,response);
        } catch (ServletException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}